#include "timer.h"

Time_Queue* time_queue_init(){
    Time_Queue* p = (Time_Queue*)calloc(1,sizeof(Time_Queue));
    return p;
}

void time_queue_destroy(Time_Queue* queue){
    for(int i=0; i<TIME_NUM; i++){
        if(queue->slot[i].size==0)
            continue;
        else{
            struct node* p_node = queue->slot[i].head;
            while(p_node!=NULL){
                struct node* temp = p_node;
                p_node = p_node->next;
                free(temp);
            }
        }
    }
    free(queue);
}

void move_next(Time_Queue* queue){
    queue->current_index ++;
    queue->current_index %= TIME_NUM;
    int index = queue->current_index;

    if(queue->slot[index].size>0){
        struct slot* p_slot = &queue->slot[index];
        struct node* p_node = p_slot->head;
        struct node* p_temp = NULL;
        while(p_node!=NULL){
            p_temp = p_node;
            p_node = p_node->next;
            delUser(p_temp->peerfd, p_temp->uid);
            free(p_temp);
        }
        p_slot->head = NULL;
        p_slot->size = 0;
    }
}

void update_node(Time_Queue* queue, int uid, int peerfd){
    int index = queue->current_index;
    struct slot* p_slot = queue->slot;
    for(int i=0; i<TIME_NUM; i++){
        struct node* p_node = (p_slot+i)->head;
        struct node* p_after = NULL;
        while(p_node!=NULL){
            if(p_node->peerfd == peerfd || p_node->uid == uid){
                if(p_after==NULL){  // 第一个结点
                    p_slot[i].head = p_node->next;
                }else{              // 非第一个结点
                    p_after->next = p_node->next;
                }

                p_slot[i].size--;
                p_slot = queue->slot+index; // p_node 指向当前结点
                p_slot->size ++;
                p_node->next = p_slot->head;
                p_slot->head = p_node;

                return ;
            }
            p_after = p_node;
            p_node = p_node->next;
        }
    }
    fprintf(stderr, "The peerfd %d and uid %d is no find int time_queue\n",peerfd,uid);
}

void insert_node(Time_Queue* queue, int uid, int peerfd){
    int index = queue->current_index;
    struct slot* p_slot = queue->slot+index;
    struct node* p_node = (struct node*)malloc(sizeof(p_node));
    p_node->peerfd = peerfd;
    p_node->uid    = uid;
    p_node->next   = p_slot->head;

    p_slot->head = p_node;
    p_slot->size ++;
}
